package me.jiatao.wan.ui.main.project

import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import me.jiatao.wan.R
import me.jiatao.wan.common.ui.LoadingLottieAnimation
import me.jiatao.wan.databinding.FragmentProjectBinding

@AndroidEntryPoint
class ProjectFragment : Fragment(R.layout.fragment_project) {

    private val mBinding: FragmentProjectBinding by viewbind()
    private val projectViewModel: ProjectViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        /** 获取分类列表 */
        projectViewModel.loadingState.observe(viewLifecycleOwner) { state ->
            mBinding.apply {
                loadingLayout.lottieAnimation.status = state
                loadingLayout.retryButton.isVisible = state == LoadingLottieAnimation.State.ERROR
            }
        }

        mBinding.loadingLayout.retryButton.setOnClickListener { _ ->
            loadData()
        }

        loadData()
    }

    /**
     * 加载分类数据
     */
    private fun loadData() {
        projectViewModel.fetchProjectTreeVM().observe(viewLifecycleOwner) { categoryTreeList ->
            mBinding.apply {
                /** 配置 */
                viewPager2.adapter = ProjectViewPagerAdapter(this@ProjectFragment, categoryTreeList)
                TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
                    tab.text = categoryTreeList[position].name
                }.attach()

                /** 关闭预加载,点击当前tab，创建fragment */
                viewPager2.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
                /** 缓存所有加载项，避免销毁二次加载数据 */
                (viewPager2.getChildAt(0) as RecyclerView).setItemViewCacheSize(categoryTreeList.size - 1)
            }
        }
    }
}